<template>
  <div>
    <basic-container>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>推荐位管理</el-breadcrumb-item>
        <el-breadcrumb-item>阅读器</el-breadcrumb-item>
        <el-breadcrumb-item>广告解锁推荐书籍</el-breadcrumb-item>
      </el-breadcrumb>
    </basic-container>
    <basic-container>
      <avue-crud
        class="exclusive"
        :table-loading="loading"
        ref="crud"
        :data="data"
        v-model="form"
        :option="option"
        :page.sync="page"
        @on-load="getList"
        @refresh-change="refreshChange"
        @search-reset="from = {}"
        @search-change="searchChange"
        @row-update="rowUpdate"
        @row-del="rowDel"
        @row-save="rowSave"
      >
      <template slot="last" slot-scope="scope">
        {{ scope.row.edit_time }}
        <el-tag>{{ scope.row.edit_account_name }}</el-tag>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button
          type="text"
          size="small"
          @click.stop="bookDetail(scope)">
          书籍详情
        </el-button>
      </template>
      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import { common } from "@/api/cat/httpRequest";
import { catUrl } from "@/config/env";

import { advertRecommendBook as baseURL, uploadFile } from "@/api/cat/baseUrls";

export default {
  data() {
    // 验证textarea行数 且不为空
    var validateBookId = (rule, value, callback) => {
      if(value === '') {
        callback(new Error('请输入书籍ID'));
      } else {
        let arr = Array.from(new Set(value.replace(/\s*/g,"").split(',')))
        if(arr.length < 1) {
          callback(new Error('书籍ID不能少于1个'));
        } else {
          callback();
        }
      }
    }
    return {
      loading: false,
      page: {
        total: 0,
        pageSize: 10,
      },
      type: true,
      data: [],
      params: {},
      form: {},
      default: {
        orderByList: "create_time&DESC",
      },
      option: {
        index: true,
        indexLabel: "编号",
        excelBtn: false,
        border: true,
        dialogModal: true,
        tip: true,
        dialogClickModal: false,
        column: [
          {
            label: "语言",
            prop: "language",
            type: "select",
            search: true,
            placeholder: "请选择语言",
            dicData: [
              {
                label: "英语",
                value: 2,
              },
              {
                label: "芬兰语",
                value: 3,
              }
            ],
            props: {
              label: "label",
              value: "value",
            },
            rules: [
              {
                required: true,
                message: "请选择语言类型",
              },
            ]
          },
          {
            label: "推荐位",
            prop: "name",
            type: 'select',
             dicData: [
              {
                label: "Read Other",
                value: "Read Other",
              }
            ],
            rules: [
              {
                required: true,
                message: "推荐位名称必须填写",
              },
            ],
          },
           {
            label: "阅读偏好",
            prop: "preference",
            type: "select",
            placeholder: "请选择偏好",
            dicData: [
              {
                label: "男",
                value: 1,
              },
              {
                label: "女",
                value: 2,
              }
            ],
            props: {
              label: "label",
              value: "value",
            },
            rules: [
              {
                required: true,
                message: "请选择",
              },
            ]
          },
          {
            label: "书籍id",
            prop: "book_ids",
            type: "textarea",
            search: false,
            span: 24,
            rules: [
              {
                required: true,
                validator: validateBookId,
                trigger: 'blur'
              },
            ],
          },
          {
             label: "最后操作信息",
            prop: "last",
            type: "input",
            slot: true,
            addDisplay: false,
            editDisplay: false,
            addDisabled: true,
            editDisabled: true,
          },
        ],
      },
    };
  },
  methods: {
    /**书籍详情 */
    async bookDetail(scope) {
      this.$router.push({ path: '/featuredFirst/advertBookinfo', query: {
        name: '广告解锁推荐书籍',
        id: scope.row.id,
      } })
    },

    /**获取列表 */
    async getList() {
      this.loading = true;
      //清空表格列表
      this.data = [];
      //发送请求获取数据
      let response = await common(
        baseURL.list,
        { ...this.params },
        "GET"
      );
      response.data.forEach(item => {
        item.book_ids = item.book_ids.join()
      });
      this.data = response.data || [];
      console.log(response);
      this.loading = false;
    },
    /**修改 */
    async rowUpdate(row, index, done, loading) {
      let userInfo = this.$store.state.user.userInfo;
      let data = {
        id: row.id,
        name: row.name,
        language: row.language,
        preference: row.preference,
        book_ids: Array.from(new Set(row.book_ids.replace(/\s*/g,"").split(','))),
        edit_account_id: userInfo.id,
        edit_account_name: userInfo.username,
      }
      let res = await common(baseURL.update, data, null, "PUT");
      if (res == null) {
        loading();
        return;
      }
      this.getList();
      done();
    },
    /**新增 */
    async rowSave(row, done, loading) {
      delete row["id"];
      let userInfo = this.$store.state.user.userInfo;
      row.edit_account_id = userInfo.id;
      row.edit_account_name = userInfo.username;
      row.book_ids = row.book_ids.split(',')
      let data = await common(baseURL.add, row, null, "POST");
      if (data == null) {
        loading();
        return;
      }
      this.getList();
      done();
    },
    /**删除 */
    rowDel(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        type: "warning",
      })
        .then(async () => {
          let userInfo = this.$store.state.user.userInfo;
          let response = await common(
            `${baseURL.del}?id=${row.id}&userId=${userInfo.id}&userName=${userInfo.username}`,
            {},
            null,
            "DELETE"
          );
        })
        .then(() => {
          this.getList();
        });
    },
    /**刷新 */
    refreshChange() {
      this.getList();
    },
    /**搜索 */
    searchChange(params, done) {
      this.params = params;
      this.page.currentPage = 1;
      this.getList();
      if (done) done();
    },
  },
};
</script>